<template>
    <lay-table :page="page" :columns="columns" :data-source="dataSource" v-model:selected-keys="selectedKeys" resize
        :loading="loading" :default-toolbar="defaultToolbars" :height="tableHeight">
        <template v-slot:toolbar>
            <!-- 数据筛选 -->
            <lay-form :model="queryForm" ref="addTreeSpeciesForm" isLabelTooltip>
                <lay-form-item mode="inline">
                    <lay-button size="xs" type="primary" @click="handleDialogValue(null)">
                        <lay-icon type="layui-icon-addition"></lay-icon> 新增
                    </lay-button>
                    <lay-popconfirm content="确定要删除所选数据吗？确认后将无法恢复！" trigger="click" position="bottom" @confirm="remove"
                        @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
                        <lay-button size="xs" border="red" border-style="dashed">删除</lay-button>
                    </lay-popconfirm>
                </lay-form-item>

                <lay-form-item prop="city" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.city" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="市" size="xs">
                        <lay-select-option v-for="city in selectList.cityList" :key="city" :value="city"
                            :label="city"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="county" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.county" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="区/县" size="xs">
                        <lay-select-option v-for="county in selectList.countyList" :key="county" :value="county"
                            :label="county"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.town" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="乡/镇" size="xs">
                        <lay-select-option v-for="town in selectList.townList" :key="town" :value="town"
                            :label="town"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.forestClass" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="森林类别" size="xs">
                        <lay-select-option v-for="value in selectList.forestClassList" :key="value.id" :value="value"
                            :label="value"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.ecologicalZone" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="生态分区" size="xs">
                        <lay-select-option v-for="value in selectList.ecologicalZoneList" :key="value.id" :value="value"
                            :label="value"></lay-select-option>
                    </lay-select>
                </lay-form-item>
            </lay-form>
        </template>

        <template v-for="child in slotChildren" :key="child.key" v-slot:[child.customSlot]="{ row }">
            <span v-if="row[child.key] <= 0"
                style="color:red;display: block;width: 100%;height: 100%;background-color: rgb(255 149 149 / 5%);">
                {{ row[child.key] }}
            </span>
            <span v-else>{{ row[child.key] }}</span>
        </template>

        <template v-slot:operator="{ row }">
            <lay-button size="xs" border="green" @click="handleDialogValue(row)">编辑</lay-button>
        </template>

    </lay-table>
    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :resource_id="resource_id"
        :dialogTitle="dialogTitle" @initDataList="initDataList"></Dialog>
</template>

<script setup>
import { onMounted, watch, ref, reactive, computed } from 'vue'
import { layer } from '@layui/layui-vue';
import api from '@/api';
import Dialog from './dialog.vue'

const selectedKeys = ref([]);
const edingKeys = ref([])
const dataSource = ref([])
const loading = ref(true)
const queryForm = ref({
    pageNum: 1,
    pageSize: 20,
    province: ["广西"],
    city: [],
    county: [],
    town: [],
    village: [],
    forestClass: [],
    ecologicalZone: []
})
// 新增、编辑 dialog
const id = ref(-1)
const resource_id = ref(-1)
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 计算表格高度
const tableHeight = computed(() => {
    return window.innerHeight - 115 + 'px'
})

const handleDialogValue = (row) => {
    if (row) {
        id.value = row.id;
        resource_id.value = row.resource;
        dialogTitle.value = "数据修改"
    } else {
        id.value = -1;
        dialogTitle.value = "添加数据"
    }
    dialogVisible.value = true
}

const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100], total: dataSource.value.length, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
    queryForm.value.pageNum = page.current;
    queryForm.value.pageSize = page.limit;
    loading.value = true;
    initDataList();
}
// attach change handler to page prop per layui-vue new API
page.change = change;

const columns = [
    { title: "选项", type: "checkbox", fixed: "left", width: '10px' },
    // { title: "ID", key: "id", fixed: "left", align: 'center', width: '50px' },
    { title: "资源ID", key: "resource", fixed: "left", align: 'center', width: '60px' },

    { title: "省/自治区", key: "province", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "市", key: "city", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "区/县", key: "county", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "乡/镇", key: "town", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "村", key: "village", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "植被生态区", key: "vegetation_ecological_zone_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态工程区", key: "ecological_engineering_zone_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态分区", key: "ecological_zone_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "森林类别", key: "forest_class_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "事权级", key: "forest_class_level", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态分区2", key: "ecological_zone_2_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "优势树种", key: "dominant_tree_species_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "起源", key: "origin_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "年龄组", key: "age_group_name", align: 'center', ellipsisTooltip: true, hide: true, },

    { title: "有林地土壤侵蚀模数", align: 'center', children: [{ title: "X1 [t·hm⁻²·a⁻¹']", key: "X1", customSlot: "X1", align: 'center', width: '90px' }] },
    { title: "无林地土壤侵蚀模数", align: 'center', children: [{ title: "X2 [t·hm⁻²·a⁻¹']", key: "X2", customSlot: "X2", align: 'center', width: '90px' }] },
    { title: "土壤含氮量", align: 'center', children: [{ title: "N_tr [%]", key: "N_tr", customSlot: "N_tr", align: 'center', width: '70px' }] },
    { title: "土壤含磷量", align: 'center', children: [{ title: "P_tr [%]", key: "P_tr", customSlot: "P_tr", align: 'center', width: '70px' }] },
    { title: "土壤含钾量", align: 'center', children: [{ title: "K_tr [%]", key: "K_tr", customSlot: "K_tr", align: 'center', width: '70px' }] },
    { title: "土壤含有机质量", align: 'center', children: [{ title: "M_tr [%]", key: "M_tr", customSlot: "M_tr", align: 'center', width: '80px' }] },
    { title: "土壤容重", align: 'center', children: [{ title: "trrz [g·cm⁻³]", key: "trrz", customSlot: "trrz", align: 'center', width: '70px' }] },

    { title: "林木氮含量", align: 'center', children: [{ title: "N_lm [%]", key: "N_lm", customSlot: "N_lm", align: 'center', width: '70px' }] },
    { title: "林木磷含量", align: 'center', children: [{ title: "P_lm [%]", key: "P_lm", customSlot: "P_lm", align: 'center', width: '70px' }] },
    { title: "林木钾含量", align: 'center', children: [{ title: "K_lm [%]", key: "K_lm", customSlot: "K_lm", align: 'center', width: '70px' }] },
    { title: "林分净生产力", align: 'center', children: [{ title: "B_nian [t·hm⁻²·a⁻¹]", key: "B_nian", customSlot: "B_nian", align: 'center', width: '70px' }] },
    { title: "林外降水量", align: 'center', children: [{ title: "P_s [mm·a⁻¹]", key: "P_s", customSlot: "P_s", align: 'center', width: '70px' }] },
    { title: "林分年蒸散量", align: 'center', children: [{ title: "E [mm·a⁻¹]", key: "E", customSlot: "E", align: 'center', width: '70px' }] },
    { title: "林分地表快速径流量", align: 'center', children: [{ title: "C [mm·a⁻¹]", key: "C", customSlot: "C", align: 'center', width: '90px' }] },

    { title: "二氧化碳中碳含量", align: 'center', children: [{ title: "R_c [27.27%]", key: "R_c", customSlot: "R_c", align: 'center', width: '90px' }] },
    { title: "林分土壤固碳量", align: 'center', children: [{ title: "S_tr [t·hm⁻²·a⁻¹]", key: "S_tr", customSlot: "S_tr", align: 'center', width: '90px' }] },

    { title: "林分负离子浓度", align: 'center', children: [{ title: "Q_flz [个·cm⁻³]", key: "Q_flz", customSlot: "Q_flz", align: 'center', width: '80px' }] },
    { title: "负离子寿命", align: 'center', children: [{ title: "L [min]", key: "L", customSlot: "L", align: 'center', width: '80px' },] },
    { title: "吸收二氧化硫量", align: 'center', children: [{ title: "Q_SO2 [t·hm⁻²·a⁻¹]", key: "Q_SO2", customSlot: "Q_SO2", align: 'center', width: '80px' }] },
    { title: "吸收氟化物量", align: 'center', children: [{ title: "Q_F [kg·hm⁻²·a⁻¹]", key: "Q_F", customSlot: "Q_F", align: 'center', width: '90px' }] },
    { title: "吸收氮氧化物量", align: 'center', children: [{ title: "Q_NO [kg·hm⁻²·a⁻¹]", key: "Q_NO", customSlot: "Q_NO", align: 'center', width: '90px' }] },
    { title: "年滞纳TSP量", align: 'center', children: [{ title: "Q_TSP [kg·hm⁻²·a⁻¹]", key: "Q_TSP", customSlot: "Q_TSP", align: 'center', width: '90px' }] },
    { title: "叶滞纳PM10量", align: 'center', children: [{ title: "Q_PM10 [g·m⁻²]", key: "Q_PM10", customSlot: "Q_PM10", align: 'center', width: '80px' }] },
    { title: "叶滞纳PM2.5量", align: 'center', children: [{ title: "Q_PM25 [g·m⁻²]", key: "Q_PM25", customSlot: "Q_PM25", align: 'center', width: '80px' }] },
    { title: "年洗脱次数", align: 'center', children: [{ title: "n", key: "n", customSlot: "n", align: 'center', width: '80px' }] },
    { title: "叶面积指数", align: 'center', children: [{ title: "LAI", key: "LAI", customSlot: "LAI", align: 'center', width: '80px' }] },

    { title: "防风固沙面积", align: 'center', children: [{ title: "A_ffgs [hm²]", key: "A_ffgs", customSlot: "A_ffgs", align: 'center', width: '80px' }] },
    { title: "有林地风蚀模数", align: 'center', children: [{ title: "Y1 [t·hm⁻²·a⁻¹]", key: "Y1", customSlot: "Y1", align: 'center', width: '80px' }] },
    { title: "无林地风蚀模数", align: 'center', children: [{ title: "Y2 [t·hm⁻²·a⁻¹]", key: "Y2", customSlot: "Y2", align: 'center', width: '80px' }] },


    { title: "备注", key: "remark", ellipsisTooltip: true, },
    { title: "操作", key: "operator", customSlot: "operator", fixed: "right", ignoreExport: true, align: 'center', width: "80px" },
]

const defaultToolbars = [
    "filter",
    {
        icon: "layui-icon-refresh",
        title: "刷新",
        onClick: () => {
            loading.value = true;
            initDataList();
        }
    },
    "export",
]

// 获取子列
const slotChildren = computed(() =>
    // only include children that declare a customSlot to avoid generating
    // v-slot with undefined names which causes template/runtime errors
    columns.flatMap(col => (col.children || []).filter(child => child.customSlot))
)

// 下拉选择列表
const selectList = ref([])

const getSelectList = async () => {
    await api.post('resource/select', queryForm.value).then((res) => {
        if (res.code == 200) {
            selectList.value = res.data
        } else {
            layer.msg(res.msg, { icon: 2, time: 5000 });
        }
    })
}

const initDataList = async () => {
    loading.value = true
    await api.post("param/search", queryForm.value).then((res) => {
        if (res.code === 200) {
            // 将每一项的 id 转为数字
            dataSource.value = (res.data || []).map(item => ({
                ...item,
                id: Number(item.id)
            }));
            page.total = res.total;
            loading.value = false
            getSelectList();
        } else {
            layer.msg(res.msg, { icon: 2, time: 5000 });
        }
    })
}


// 删除
const remove = async (id) => {
    var ids = []
    if (id) {
        ids.push(id)
    } else {
        ids = selectedKeys.value
    }
    await api.del("param/action", ids).then((res) => {
        if (res.code == 200) {
            layer.notify({
                title: "Success",
                content: res.msg,
                icon: 1,
                time: 2000,
                offset: 'lt',
            })
            initDataList();
            selectedKeys.value = [];
        } else {
            layer.notify({
                title: "Error",
                content: res.msg,
                icon: 2,
                time: 5000,
                offset: 'lt',
            })
        }
    });
}


// 监听筛选条件变化
watch([
    () => queryForm.value.city,
    () => queryForm.value.county,
    () => queryForm.value.town,
    () => queryForm.value.forestClass,
    () => queryForm.value.ecologicalZone,
], () => {
    loading.value = true;
    initDataList();
})

onMounted(() => {
    initDataList();
    getSelectList();
})
</script>

<style scoped>
::v-deep .layui-table td {
    padding: 0 !important;
    height: 35px;
    line-height: 35px;
}

::v-deep .layui-tag-input {
    height: 22px;
}

::v-deep .layui-form-item {
    margin-bottom: 0px;
}
</style>